package com.yhq.basic.design.structural;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author hqyin
 * @date 2025/6/4 10:08 AM
 */
public class ProxyDemo {
    public static void main(String[] args) {
        //静态代理
        ImageProxy staticProxy = new ImageProxy(new ImageImpl());
        System.out.println("执行结果："+staticProxy.display());;

        //动态代理 Proxy
        Image image = (Image) Proxy.newProxyInstance(Image.class.getClassLoader(), new Class[]{Image.class}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                System.out.println("Before method: " + method.getName());
                Object result = method.invoke(new ImageImpl(), args); // 调用原始对象的方法
                System.out.println("After method: " + method.getName());
                return result;
            }
        });
        System.out.println("执行结果："+image.display());


        //动态代理 CGLIB
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(ImageImpl.class);
        enhancer.setCallback(new MethodInterceptor() {
            @Override
            public Object intercept(Object sub, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                System.out.println("======插入前置通知======");
                Object object = methodProxy.invokeSuper(sub, objects);
                System.out.println("======插入后者通知======");
                return object;
            }
        });
        Image poxy = (Image) enhancer.create();
        System.out.println(poxy.display());

    }

}

class ImageImpl implements Image {

    @Override
    public String display() {
        System.out.println("展示图片信息");
        return "执行方法";
    }
}

interface Image {
    String display();
}

class ImageProxy implements Image {
    private ImageImpl image;

    public ImageProxy(ImageImpl image) {
        this.image = image;
    }

    @Override
    public String display() {
        System.out.println("静态代理之前");
        String result = image.display();
        System.out.println("静态代理代理之后");
        return result;
    }
}
